package org.devf.fork.imsimulator.socket.handler;

//import cn.hutool.log.Log;

import org.devf.fork.imsimulator.play.MusicPlayer;
import org.devf.fork.imsimulator.play.TipAudioEnum;
import org.devf.fork.imsimulator.service.ServiceFactory;
import org.devf.fork.imsimulator.socket.Channel;
import org.devf.fork.imsimulator.socket.Ihandler;
import org.devf.fork.imsimulator.socket.dto.BasePackets;
import org.devf.fork.imsimulator.socket.dto.BizType;
import org.devf.fork.imsimulator.socket.handler.listener.ChatListener;
import org.devf.fork.imsimulator.socket.handler.listener.HandlerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * ChatHandler related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/12 14:50
 */
public class ChatHandler implements Ihandler {

    private final List<ChatListener> chatListenerList = new ArrayList<>();

    public ChatHandler() {
    }

    @Override
    public void register(HandlerListener chatListener) {
        this.chatListenerList.add((ChatListener) chatListener);
    }

    @Override
    public boolean isSupport(BasePackets packets) {
        return packets.getBizType().equals(BizType.SINGLE_CHAT.name());
    }

    @Override
    public boolean execute(Channel channel, BasePackets packets) {
        //收到聊天消息
        if (!packets.getAck()){
            //播放声音
            MusicPlayer.play(TipAudioEnum.CHAT_MESSAGE_TIP);

            //保存接收到的消息
            ServiceFactory.getChatService().saveMessageOfReceipt(packets);
        }else{
            //ACK=>更新消息
            ServiceFactory.getChatService().updateState(packets);
        }

        //通知UI
        processNotify(packets);
        return false;
    }

    private void processNotify(BasePackets packets) {
        for (ChatListener chatListener : chatListenerList) {
            chatListener.getMessage(packets);
        }
    }
}
